﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

namespace SouthernLand.Common.UrlRewrite
{
    public class UrlRewriter : IHttpModule
    {
        private HttpApplication curApp;

        #region IHttpModule Members

        public void Init(HttpApplication _app)
        {
            curApp = _app;
            curApp.BeginRequest += curApp_BeginRequest;
        }

        public void Dispose()
        {
        }

        #endregion

        public void curApp_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = curApp.Context;
            HttpRequest request = context.Request;
            string filepath = request.FilePath;
            string filepath1 = filepath.Replace("-", "");
            if (File.Exists(context.Server.MapPath(filepath))) return;
            string querystring = string.Empty;
            foreach (string key in request.QueryString.AllKeys)
            {
                querystring += "&" + key + "=" + request.QueryString[key];
            }
            string tmp = filepath.Replace(".htm", string.Empty);
            tmp = tmp.Substring(1);
            string[] param = tmp.Split("/".ToCharArray());
            List<RuleInfo> _lstRule = RuleController.GetRules();
            string rewritepath = string.Empty;
            foreach (RuleInfo rule in _lstRule)
            {
                var r = new Regex(rule.Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (r.IsMatch(filepath1))
                {
                    rewritepath = Globals.ApplicationPath +
                                  String.Format(rule.SendTo, param).Replace(Convert.ToChar(13).ToString(), "");
                    break;
                }
            }
            if (rewritepath != string.Empty)
            {
                if (querystring != string.Empty)
                    rewritepath += querystring.Replace(Convert.ToChar(13).ToString(), "");

                context.RewritePath(rewritepath);
            }
        }
    }
}